package com.itheima.config;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.itheima.common.R;
import com.itheima.utils.JwtUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录拦截器
 */
@Configuration
public class LoginInterceptor implements HandlerInterceptor {
    //private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, Object> map = new HashMap<>();
        //令牌是放在请求头中，获取请求头中令牌
        String token = request.getHeader("token");
        try {
            JwtUtils.verify(token);//验证令牌
            return true;//放行请求

        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            response.getWriter().write(JSON.toJSONString(R.error("无效签名")));
            return false;
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            response.getWriter().write(JSON.toJSONString(R.error("toten过期")));
            return false;
        } catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            response.getWriter().write(JSON.toJSONString(R.error("token算法不一致")));
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write(JSON.toJSONString(R.error("token失效")));
            return false;
        }

        // map.put("state", false);//设置状态
        // //将map转化成json，response使用的是Jackson
        // String json = new ObjectMapper().writeValueAsString(map);
        // response.setContentType("application/json;charset=UTF-8");
        // response.getWriter().print(json);
        // return false;
    }
}
